<template>
  <!-- 模态框 -->
  <div class="modal">
    asdf
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginBox">
      <!-- 关闭 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <section class="nav">
        <a href="#" :class="{ active: isShowPhone }" @click="isShowPhone = true">手机号登录 </a> |
        <a href="#" :class="{ active: !isShowPhone }" @click="showQrCode">微信扫码登录 </a>
      </section>
      <div class="content">
        <!-- 手机号  -->
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input type="text" placeholder="请输入手机号" v-model="PhoneNumber" class="ipt" />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :accuracy="40"
              :imgs="arr"
            ></slide-verify>
          </div>
          <div class="row">
            <input type="text" v-model="code" placeholder="请输入短信验证码" class="ipt" />
            <!-- 分成两个按钮是为了，避免事件冒泡 -->
            <!-- <button class="btncode">{{ msg }}</button> -->
            <button class="btncode" v-show="isShowCount" @click="getCode">获取验证码</button>
            <button class="btncode" v-show="!isShowCount">{{ count }}</button>
          </div>
          <div class="row">
            <button class="btnlogin ipt" @click="Login">登录</button>
          </div>
        </div>
        <!--扫码 -->
        <div class="qrLogin qrcode" id="weixin" v-show="!isShowPhone">11111</div>
      </div>
    </div>
  </div>
</template>
 
<script>
import { mapMutations, mapActions } from 'vuex'
import { Login1, state1, bingApi } from '@/request/api'
import { vaidatePhoneNumber } from '@/utils'
export default {
  data() {
    return {
      isShowPhone: true,
      msg: '向右滑动',
      PhoneNumber: '',
      count: 10,
      isShowCount: true,
      code: '',
      arr: [
        require('../assets/img/integral-01.9386d4bf.png'),
        require('../assets/img/integral-02.150d92a1.png'),
        require('../assets/img/integral-03.9870f3f1.png'),
        require('../assets/img/integral-04.afadcbdf.png')
      ]
    }
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: 'showModal/changeIsShowLoginModal',
      changeIsLogined: 'LoginStatus/changeIsLogined',
      changeIsShowToast: 'showToast/changeIsShowToast'
    }),
    ...mapActions({
      asyncchangeIsShowToast: 'showToast/asyncchangeIsShowToast',
      asyncChangeUserInfo: 'userInfo1/asyncChangeUserInfo'
    }),
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1)
      this.msg = 'login success, 耗时 ' + ms + 's'
    },
    // 拼图失败
    onFail() {
      this.onRefresh() // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = '再试一次'
    },
    /* 倒计时，循环定时器递减数字count */
    daojishi() {
      this.isShowCount = false
      let time = setInterval(() => {
        this.count--
        if (this.count <= 0) {
          this.count = 10
          this.isShowCount = true
          clearInterval(time)
        }
      }, 1000)
    },
    showQrCode() {
      this.isShowPhone = false
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this
      new WxLogin({
        id: 'weixin',
        appid: 'wx67cfaf9e3ad31a0d', // 这个appid要填死
        scope: 'snsapi_login',
        // 扫码成功后重定向的接口
        redirect_uri: 'https://sc.wolfcode.cn/cms/wechatUsers/shop/PC',
        // state填写编码后的url
        state: encodeURIComponent(window.btoa('http://127.0.0.1:8081' + _this.$route.path)),
        // 调用样式文件
        href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICBkaXNwbGF5OiBub25lOw0KfSAgICANCi5pbXBvd2VyQm94IHFyY29kZXsNCiAgbWFyZ2luLXRvcDogMjBweDsNCn0='
      })
    },
    /* 将正则和滑块进行封装 */
    toVerify() {
      if (!vaidatePhoneNumber(this.PhoneNumber)) {
        /*       alert('请输入正确的手机号码') */
        //用toast来测试下toast组件是否有被使用到
        this.asyncchangeIsShowToast({
          isshow: true,
          msg: '请输入正确的手机号码',
          type: 'success'
        })
        // setTimeout(() => {
        //   this.changeIsShowToast({
        //     isshow: false
        //   })
        // }, 1000)
        return
      }
      /* 对滑块进行判断  */
      if (this.msg == '向右滑动' || this.msg == '再试一次') {
        // alert('请正确滑动滑块')
        this.asyncchangeIsShowToast({
          isshow: true,
          msg: '请正确滑动滑块',
          type: 'danger'
        })
        return
      }
      return true //如果都正确就返回真
    },
    //登录
    async Login() {
      /* 手机判断和滑块判断  */
      if (!this.toVerify()) return
      /* 对验证码进行判断  */
      if (!this.code.trim()) {
        alert('验证码不能为空')
        return
      }
      let uuid = localStorage.getItem('uuid')
      let res = null
      if (uuid) {
        res = await bingApi({
          verifyCode: this.code,
          phone: this.PhoneNumber,
          uuid
        })
      } else {
        res = await Login1({
          verifyCode: this.code,
          phone: this.PhoneNumber
        })
      }

      /* 有进行响应拦截，如果返回的是undefind 就return */
      if (!res) return
      console.log(res)
      //提示
      alert('登录成功')
      //保存token  obj['a']  obj.a
      localStorage.setItem('x-auth-token', res.data['x-auth-token'])
      //关闭模态框  从store 映射到本组件的
      this.changeIsLogined(true)
      this.changeIsShowLoginModal(false)
      uuid && this.$router.push(this.$route.path)
      localStorage.removeItem('uuid')
      this.asyncChangeUserInfo()
      // topbar中登录状态的切换
    },
    /* 点击获取验证码 */
    async getCode() {
      /* 对输入的手机号码进行正则判断  */
      // let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      // if (!reg.test(this.PhoneNumber)) {
      //   alert('手机格式有错，请重新输入')
      //   return
      // }

      /* 发送请求 得到验证码 */
      /* 接收上面两上判断返回的值  */
      let flag = this.toVerify()
      if (!flag) return
      let res = await state1({
        phone: this.PhoneNumber
      })
      console.log(res)
      if (!res) return

      if (res.code != 0) {
        this.daojishi()
      }
    }
    // getCode() {
    //   let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    //   if (!reg.test(this.PhoneNumber)) {
    //     alert('请输入正确的手机号码')
    //     return
    //   }
    //   if (this.msg == '再试一次' || this.msg == '向右滑动') {
    //     alert('请滑动滑块')
    //     return ;
    //   }
    //   let time= setInterval(()=>{
    //     this.count--;
    //     if(this.count<=0){

    //     }
    //   })
    // }
  }
}
</script>
 
<style lang = "less" scoped>
#weixin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    width: 555px;
    height: 423px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    background: url('../assets/img/login-box-bg.png');
    .close {
      position: absolute;
      right: 60px;
      top: 40px;
      width: 20px;
      height: 20px;
      background: url('../assets/img/close.png');
    }
  }
  .nav {
    padding-top: 50px;
    text-align: center;

    a {
      text-decoration: none;
      color: gray;
      &.active {
        color: #000;
      }
    }
  }
  .content {
    background: pink;
    width: 355px;
    height: 300px;
    margin: 10px auto 0;
    /* 登录样式 */
    .row {
      display: flex;
      margin-bottom: 20px;
      .ipt {
        height: 50px;
        outline: none;
        flex: 1;
        text-indent: 1em;
      }
      .btncode {
        background-color: #0a328e;
        color: #fff;
        width: 100px;
      }
      .btnlogin {
        background-color: #0a328e;
        color: #fff;
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>